package com.fetch.fetcher;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import com.fetch.Main;
import com.fetch.bean.Profile;
import com.fetch.common.Configuration;
import com.fetch.common.Constants;
import com.fetch.common.LOG;


public class DetailFetcher {
	private String basepath = "";
	private HttpClient client = new HttpClient();
	public int currPape = 1;
	
	public void fetch(Profile profile){
		basepath = Configuration.getString("filepath") + "/" + Constants.getCategouyName(profile.getCategory()) + "/" + profile.getName() + "(" + profile.getDate() + ")";
		basepath = basepath.replace("****", profile.getId());
		PostMethod getMethod = null;
		File file = new File(basepath);
		if(!file.exists()){
			file.mkdirs();
		}
		try{
			String url = "http://218.4.189.213:8001/CorpSel/Corp_info.aspx?corp_id=";
			if(Constants.CATEGORY_PERSON == profile.getCategory()){
				url = "http://218.4.189.213:8001/CorpSel/Corp_infoG.aspx?corp_id=";
			}
			getMethod = new PostMethod(url + profile.getId());
			getMethod.addRequestHeader("Cookie", Main.COOKIE);
			client.executeMethod(getMethod);
			String result = getMethod.getResponseBodyAsString();
//			writeFile(profile.getId(), result);
			parse(result);
			LOG.info(Constants.getCategouyName(profile.getCategory()) + " -> " + profile.getName() + " " + profile.getDate());
		}catch (Exception e) {
			e.printStackTrace();
			String[] files = file.list();
			for (int i = 0; i < files.length; i++) {
				File f = new File(basepath + "/" + files[i]);
				if(f.exists()){
					f.delete();
				}
			}
			file.delete();
		}finally{
			getMethod.releaseConnection();
		}
	}
	
	private void parse(String source) throws Exception{
		int startIndex = source.indexOf("background=\"../image/bj2s.gif\"");
		int endIndex = source.indexOf("src=\"../image/bj3s.gif\"");
		source = source.substring(startIndex, endIndex);
		
		Pattern namePttern = Pattern.compile("<td.*?>(.*?)</td>");
		Pattern codePttern = Pattern.compile("InfoShowImg.aspx\\?StrCode=(.*?)\"");
		Pattern pattern = Pattern.compile("<tr>([\\s\\S]*?)</tr>");
		Matcher matcher = pattern.matcher(source);
		while(matcher.find() && Main.self.started){
			String sub = matcher.group(1);
			Matcher nameMatch = namePttern.matcher(sub);
			Matcher codeMatch = codePttern.matcher(sub);
			if(nameMatch.find() && codeMatch.find()){
				String name = nameMatch.group(1).replaceAll("&nbsp;| ", "");
				String code = codeMatch.group(1);
				download(name, code);
			}
		}
	}
	
	private void download(String name, String code) throws Exception{
		GetMethod getMethod = new GetMethod("http://218.4.189.213:8001/CorpSel/InfoShowImg.aspx?StrCode=" + code);
		client.executeMethod(getMethod);
		byte[] b = getMethod.getResponseBody();
		FileOutputStream fos = new FileOutputStream(new File(basepath + "/" + name + ".jpg"));
		fos.write(b);
		fos.close();
		getMethod.releaseConnection();
	}
	
//	private void writeFile(String compId, String source){
//		FileOutputStream fos = null;
//		try{
//			String path = Configuration.getString("filepath") + "/pages/" + currPape + "/" + compId + ".html";
//			File file = new File(path);
//			if(!file.getParentFile().exists()){
//				file.getParentFile().mkdirs();
//			}
//			fos = new FileOutputStream(file);
//			fos.write(source.getBytes());
//		}catch (Exception e) {
//			e.printStackTrace();
//		}finally{
//			try {
//				fos.close();
//			} catch (Exception e2) {}
//		}
//	}
	
	public void close(){
		try{
			client.getHttpConnectionManager().closeIdleConnections(0);
		}catch (Exception e) {
		}
	}
	
}
